package top.mistgc.mall.exception;

import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ResponseBody;
import top.mistgc.mall.common.Result;

import java.util.List;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * handle runtime excepion
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Result exceptionHandler() {
        return new Result<>().error();
    }


    /**
     * handle custom excepion
     */
    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public Result customExceptionHandler(CustomException e) {
        log.error("Error Reason: " + e.getMessage());
        return new Result<>().error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public Result MethodArgumentNotValidException(MethodArgumentNotValidException e) {
        // get all errors
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        String errorText = "";
        for (int i = 0; i < fieldErrors.toArray().length; i++) {
            errorText += fieldErrors.get(i).getDefaultMessage();
        }
        log.error("Error Reason: " + errorText);
        return new Result<>().error(errorText);
    }
}
